// 定义用户相关仓库
import { reqGetCode, reqUserLogin } from '@/apis/hospital'
import { LoginData } from '@/apis/hospital/type'
import { defineStore } from 'pinia'
import { UserState } from './interface'
import type { UserInfo } from '@/apis/hospital/type'
import { REMOVE_TOKEN } from '@/utils/user'

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      visiable: false,//用于控制登录组件的显示与隐藏
      code: '',
      userInfo: ({token:'', username:''})
    }
  },
  getters: {
    // 计算属性
  },
  actions: {
    // 方法
    async getCode(phone: string) {
      const res: any = await reqGetCode(phone)
      if (res.code === 200) {
        this.code = res.data
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async userLogin(loginData: LoginData) {
      const res = await reqUserLogin(loginData)
      // console.log(res)
      if (res.code === 200) {
        this.userInfo.token = res.data.token
        this.userInfo.userName = res.data.name
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    logout() {
      this.userInfo = { name: '', token: '' } as UserInfo
      REMOVE_TOKEN()
    },
  },
  persist: {
    key: 'user',
    storage: window.localStorage,
    // paths: ['userInfo'] 
  }
})

export default useUserStore
